package com.ruiysoft.crm.controller;


import cn.taroco.common.utils.Query;
import cn.taroco.common.vo.SysRole;
import cn.taroco.common.vo.UserVO;
import cn.taroco.common.web.Response;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.ruiysoft.crm.log.InvokeLog;
import com.ruiysoft.crm.model.dto.BizPolicyDTO;
import com.ruiysoft.crm.model.entity.BizClient;
import com.ruiysoft.crm.model.entity.BizPolicy;
import com.ruiysoft.crm.model.entity.SysUser;
import com.ruiysoft.crm.service.BizClientService;
import com.ruiysoft.crm.service.BizPolicyService;
import com.ruiysoft.crm.service.SysUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

/**
 * @author fanyl5
 */
@Slf4j
@RestController
@RequestMapping("/policy")
public class BizPolicyController {

    private final SysUserService sysUserService;

    private final BizPolicyService bizPolicyService;

    private final BizClientService bizClientService;


    public BizPolicyController(BizPolicyService bizPolicyService, SysUserService sysUserService, BizClientService bizClientService) {
        this.bizPolicyService = bizPolicyService;
        this.sysUserService = sysUserService;
        this.bizClientService = bizClientService;
    }

    @InvokeLog
    @PostMapping("/insert")
    public Response insert(@RequestBody BizPolicyDTO bizPolicyDTO, UserVO userVO) {
        BizPolicy bizPolicy = new BizPolicy();
        BeanUtils.copyProperties(bizPolicyDTO, bizPolicy);

        if (StringUtils.hasText(userVO.getUsername())) {
            SysUser sysUser = sysUserService.getOne(new QueryWrapper<SysUser>().lambda().eq(SysUser::getUsername, userVO.getUsername()));
            bizPolicy.setUserId(sysUser.getUserId());
            bizPolicy.setUserName(sysUser.getUsername());
            bizPolicy.setUserRealName(sysUser.getRealName());
        }
        //新建保单默认为未出单状态
        bizPolicy.setPolicyStatus("-1");
        bizPolicy.setCreateDate(LocalDateTime.now());
        return Response.success(bizPolicyService.save(bizPolicy));
    }

    @InvokeLog
    @GetMapping("/get/{id}")
    public Response get(@PathVariable Integer id) {
        return Response.success(bizPolicyService.getPolicyById(id));
    }

    @InvokeLog
    @DeleteMapping("/delete/{id}")
    public Response delete(@PathVariable Integer id) {
        return Response.success(bizPolicyService.removeById(id));
    }

    @InvokeLog
    @PutMapping("/update")
    public Response editDict(@RequestBody BizPolicy bizPolicy) {
        bizPolicy.setModificationDate(LocalDateTime.now());
        if ("policyStatus_01".equalsIgnoreCase(bizPolicy.getPolicyStatus())) {
            bizPolicy.setBilldate(LocalDateTime.now());
            //更新客户信息的交强险、商业险日期
            int clientId = bizPolicy.getClientId();
            if (clientId > 0) {
                BizClient bizClient = bizClientService.getById(clientId);
                if (!ObjectUtils.isEmpty(bizClient.getClivtaEndDate())) {
                    bizClient.setClivtaEndDate(bizClient.getClivtaEndDate().plusYears(1));
                }
                if (!ObjectUtils.isEmpty(bizClient.getViEndDate())) {
                    bizClient.setViEndDate(bizClient.getViEndDate().plusYears(1));
                }
                bizClientService.updateById(bizClient);
            }
        }
        return Response.success(bizPolicyService.updateById(bizPolicy));
    }


    @InvokeLog
    @Transactional(rollbackFor = Exception.class)
    @DeleteMapping("/delete/batch")
    public Response deleteBatch(@RequestBody List<Integer> ids) {
        if (ObjectUtils.isEmpty(ids)) {
            return Response.failure("参数不能为空");
        }
        return Response.success(bizPolicyService.removeByIds(ids));
    }


    @InvokeLog
    @GetMapping("/list/page")
    public IPage policyPage(@RequestParam Map<String, Object> params, UserVO userVO) {
        List<SysRole> sysRoleList = null;
        if (!ObjectUtils.isEmpty(userVO)) {
            sysRoleList = userVO.getRoleList();
            if (!CollectionUtils.isEmpty(sysRoleList)) {
                //判断是否具备出单员角色，出单员可查询所有保单
                if (sysRoleList.stream().noneMatch(sysRole -> "chudanyuan".equals(sysRole.getRoleCode()))) {
                    String userName = userVO.getUsername();
                    if (StringUtils.hasText(userName)) {
                        int userId = sysUserService.getUserIdByUserName(userName);
                        params.put("user_id", userId);
                    }
                }
            }
        }

        return bizPolicyService.queryPolicyList(new Query<>(params));
    }

}
